package com.fmdj.odr.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@Slf4j
public class QuartzUtil {

    @Resource
    private Scheduler scheduler;

    /**
     * 添加定时器
     * @param jobDetail 任务
     * @param jobName 任务名称
     * @param jobGroupName 任务组名
     * @param start 开始的日期
     */
    public void addJob(JobDetail jobDetail, String jobName, String jobGroupName, Date start) {
        try {
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroupName)
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule().withMisfireHandlingInstructionFireNow())//假如定时12:00执行,11:00的时候终止了程序
                                                                                                                 //13:00启动程序,会立即执行之前没执行的定时器
                    .startAt(start).build();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            log.error("定时器添加失败", e);
        }
    }

    /**
     * 查询定时器
     * @param jobName
     * @param jobGroupName
     * @return
     */
    public boolean checkExists(String jobName,String jobGroupName) {
        TriggerKey triggerKey = new TriggerKey(jobName, jobGroupName);
        try {
            return scheduler.checkExists(triggerKey);
        } catch (SchedulerException e) {
            log.error("定时器查询失败", e);
            return false;
        }
    }

    /**
     * 删除定时器
     * @param jobName
     * @param jobGroupName
     */
    public void deleteJob(String jobName, String jobGroupName) {
        try {
            TriggerKey triggerKey = new TriggerKey(jobName, jobGroupName);
            scheduler.pauseTrigger(triggerKey);
            scheduler.unscheduleJob(triggerKey);
            scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));
        } catch (SchedulerException e) {
            log.error("定时器删除失败", e);
        }
    }


}
